package demo.java.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import demo.java.io.IoDemo;

public class PropertiesDemo {

    static void testProperties() throws IOException {
        Properties properties = new Properties();

        InputStream is = MapDemo.class.getResourceAsStream("d:/test/aaa.properties");
        properties.load(is);

        Set<Object> set = properties.keySet();
        Iterator<Object> iterator = set.iterator();
        while (iterator.hasNext()) {
            Object key = (Object) iterator.next();
            System.out.println(key.toString() + " = " + properties.getProperty((String) key));
        }

        properties = System.getProperties();
    }

    /**
     * 该方式只能读取类路径下的配置文件，有局限但是如果配置文件在类路径下比较方便。
     * 
     * @throws IOException
     */
    public void test1() throws IOException {
        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = IoDemo.class.getClassLoader().getResourceAsStream("config/config.properties");
        // 使用properties对象加载输入流
        properties.load(in);
        // 获取key对应的value值
        properties.getProperty("key1");
    }

    /**
     * 该方式的优点在于可以读取任意路径下的配置文件
     * 
     * @throws IOException
     */
    public void test2() throws IOException {
        Properties properties = new Properties();
        // 使用InPutStream流读取properties文件
        BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
        properties.load(bufferedReader);
        // 获取key对应的value值
        properties.getProperty("key1");
    }
}
